package middleware

import (
	"admin/database"
	"admin/model"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

var db *gorm.DB = database.Db()

func Cors(c *gin.Context) {
	method := c.Request.Method
	c.Header("Access-Control-Allow-Origin", "*")
	c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
	c.Header("Access-Control-Allow-Methods", "*")
	c.Header("Access-Control-Allow-Credentials", "true")

	//放行所有OPTIONS方法
	if method == "OPTIONS" {
		c.AbortWithStatus(http.StatusNoContent)
	}
	// 处理请求
	c.Next()
}

func Auth(ctx *gin.Context) {
	authorization := ctx.GetHeader("Authorization")
	data := strings.Split(authorization, " ")
	token := ""
	if len(data) == 2 {
		if len(data) >= 1 && data[0] == "Bearer" {
			token = data[1]
		} else {
			ctx.AbortWithStatusJSON(200, gin.H{
				"code":    403,
				"message": "无效鉴权[无效的鉴权头]",
			})
			return
		}
	} else {
		ctx.AbortWithStatusJSON(200, gin.H{
			"code":    403,
			"message": "无效鉴权[鉴权格式不正确]",
		})
		return
	}
	user := model.User{}
	count := db.Where("token = ?", token).Find(&user).RowsAffected
	if count == 0 {
		ctx.AbortWithStatusJSON(200, gin.H{
			"code":    403,
			"message": "用户token是无效的",
		})
		return
	}
	ctx.Set("user", user)
	ctx.Next()
}
